package com.liebaut.dao.util;

import com.liebaut.model.person.Customer_;
import com.liebaut.model.person.Customer;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.metamodel.SingularAttribute;
import java.util.ArrayList;

/**
 * Created by Dirk on 7/04/14.
 */
public class CustomerSpecifications{

    public static Specification<Customer> searchCustomer(final String name, final String extraName, final String number){
        return new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> customerRoot, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                ArrayList<Predicate> predicates = new ArrayList<Predicate>();
                if(name != null && !name.equals(""))
                    predicates.add(createPredicate(Customer_.name, name, criteriaBuilder, customerRoot));
                if(extraName != null && !extraName.equals(""))
                    predicates.add(createPredicate(Customer_.extraName, extraName, criteriaBuilder, customerRoot));
                if(number != null && !number.equals(""))
                    predicates.add(createPredicate(Customer_.number, number, criteriaBuilder, customerRoot));
                return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
            }

            private String getLikePattern(final String searchTerm) {
                if(searchTerm == null)
                    return "%";
                StringBuilder pattern = new StringBuilder();
                pattern.append("%");
                pattern.append(searchTerm.toLowerCase());
                pattern.append("%");
                return pattern.toString();
            }

            private Predicate createPredicate(final SingularAttribute attribute, final String pattern, final CriteriaBuilder criteriaBuilder, final Root<Customer> customerRoot){
                return criteriaBuilder.like(criteriaBuilder.lower(customerRoot.<String>get(attribute)), getLikePattern(pattern));
            }

        };
    }


}
